/**
 * @file 用户信息
 * @author liushuang(liushuang04@baijia.com)
 * @date 2019-11-06
 */
import {getMenuList as menuListApi} from '~/service/reports';
// 菜单配置
import {formatMenu} from '~/utils/common/menuConfig';

export default {
    state: {
        menuList: [],
        userId: null,
        displayName: '',
        roleList: [],
        selectRole: null,
        // 权限tag
        hasPermissions: [],
    },

    action: {
        getUserInfo(payload) {
            return payload;
        },
        getMenuList(payload) {
            return menuListApi(payload);
        }
    },

    reducer: {
        getUserInfo(state, action) {
            const {payload} = action;
            if (payload && payload.displayName) {
                // 设置localStorage
                let selectRole = null;
                const hasRolesFilter = payload.hasRoles.filter(item =>
                    item.hasPermissions.findIndex(ele => ele.tag === 'portal_login') > -1);
                if (!window.localStorage.roleId
                    || hasRolesFilter.findIndex(item => item.id.toString() === window.localStorage.roleId) === -1) {
                    window.localStorage.setItem('roleId', hasRolesFilter[0].id);
                    selectRole = hasRolesFilter;
                }
                else {
                    selectRole = hasRolesFilter.filter(item => item.id.toString() === window.localStorage.roleId);
                }
                let hasPermissions = [];
                for (let i = 0; i < hasRolesFilter.length; i++) {
                    hasPermissions = hasPermissions.concat(hasRolesFilter[i].hasPermissions);
                }
                return {
                    ...state,
                    userId: payload.id,
                    roleId: payload.roleId,
                    displayName: payload.displayName,
                    roleList: hasRolesFilter,
                    hasPermissions,
                    selectRole: selectRole[0],
                };
            }

            return {...state};
        },
        getMenuList(state, action, error) {
            if (!error) {
                let {data} = action.payload;
                // 格式化报表，添加 path属性
                data = formatMenu(data);
                return {
                    ...state,
                    menuList: data,
                };
            }
        }
    }
};
